<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/5
 * Time: 14:15
 */
namespace app\index\controller;
use app\common\controller\PayBase;
use think\Db;
use app\index\model\ChongzhiList;
use think\Exception;

class Payby extends PayBase{

    private $merId;         //商户号
    private $key;           //
    private $backUrl;
    private $returnUrl;
    private $payUrl;
    public function __construct(){
        parent::__construct();
        $this->merId = '180426165413747';
        $this->key = '893b6277ac6ba6fb102720d4891c3dc3';
        $this->backUrl = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Payby/backUrl';
        $this->returnUrl = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Payby/returnUrl';
        $this->payUrl = 'http://pay.88uyx.com/guanjun/pay/BgTrans';
    }
    public function initPay($username='',$pay_type='',$amount=-1,$from=0){
        //接收数据

        $user = cookie('username','');
        $password = cookie('password','');
        $username =  empty($username) ? input('post.username','') : $username;
        $bank_code = empty($pay_type) ? input('post.pay_type','') : $pay_type;
        $amount = -1==$amount ? input('post.amount',0) : $amount;
        $ctime = time();

        if($bank_code=='null' || $bank_code=='') return packJson('','请选择支付方式',500);
        $pay_method = Db::name('pay_type_list')
            ->alias("a")
            ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
            ->where(['a.method'=>8,'a.type_value'=>$bank_code])
            ->field('a.type_name,b.name,b.id,b.method,b.money')->find();
        $remark = $pay_method['type_name'].'-'.$pay_method['name'];
        //验证用户信息
        if( 0==$from ){
            if(!$user || !$username || ($user!=$username)) return packJson('','用户身份验证失败',500);
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username,'password'=>$password])->find();
        }else{
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username])->find();
        }
        if(!$user_info) return packJson('','用户身份验证失败',500);
        if($user_info['swzh'] == 1) return packJson('','试玩账号无法充值',500);
        if($user_info['nbzh'] == 1) return packJson('','内部账号不支持线上充值',500);

        //充值防骚扰是否开启，并进行处理
        $harassment = Db::name('xt_czfsr')->find();
        if($harassment['open'] > 0) {
            $nowys = $ctime - $harassment['time_xs'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username',$username)->where('cztime','>',$nowys)->find();
            if($old_czjl['id'] > 0) {
                return packJson('',"系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！",500);
            }
        }
        //验证金额
        if($amount <= 0) return packJson('','请输入充值金额',500);
        if($amount < 50) return packJson('','最低充值金额为五十元人民币',500);
        if($amount > 20000) return packJson('','充值金额超过范围',500);

        //计算优惠金额
        $msje = $msbs = 0;
        $cz_set = Db::name('xt_chongzhi')->find();
        $user_class = Db::name('us_class')->where('id',$user_info['us_class'])->find();
        $zsje = $amount * $user_class['czzsbl'] / 100;
        $zsbs = $user_class['czzsbl'];
        if($amount >= $cz_set['xscz_je']) {
            $msje = $amount * $cz_set['xscz_zs'] / 100;
            $msbs = $cz_set['xscz_zs'];
        }
        //充值方案赠送
        $method_money = 0.00;
        if( floatval( $pay_method['money'] ) > 0 ){
            if( 0==intval( $pay_method['method'] ) ){
                //金额
                $method_money = $pay_method['money'];
            }else{
                //比例
                $method_money = floatval($amount) * floatval($pay_method['money']) / 100;
            }
        }
        $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));
        //生成订单号
        $order_sn = 'BYF' . str_pad($user_info['id'],5,'0',STR_PAD_LEFT) . $ctime . rand(111,999);
        //处理数据并生成签名
        if( 1==$from ) $this->returnUrl.="Third";
        $data = [
            'merId' => $this->merId,
            'merOrderId' => $order_sn,
            'paymentType' => $bank_code,
            'transAmt' => strval($amount*100),
            'goodsTitle' => '邦银支付',
            'backUrl' => $this->backUrl,
            'returnUrl'=>$this->returnUrl,
        ];
        if( !strpos($bank_code,'_') ){
            $data['paymentType'] = 'gate_web';
            $data['bankCode'] = $bank_code;
        }

        ksort($data);
        $msg = $this->signMsg($data, $this->key);
        $data['sign'] = strtoupper(md5($msg));

        $return_val = HttpClient::quickPost($this->payUrl,$data);
        $finnal_return_value = json_decode($return_val,true);
        if( $finnal_return_value['success'] ){
            //插入充值信息
            $model = new ChongzhiList();
            if($model->setTransRechargeInfo($order_sn,$amount,$username,0,0,1,$remark,$ctime,'邦银线上支付','系统自动',get_ip(),0,$bank_code,$zsje,$zsbs,$msje,$msbs,$user_info['us_class'],'',0,$method_money)){
                return packJson($finnal_return_value['imgUrl'],'',200);
            }else{
                return packJson('',"订单生产错误",500);
            }
            //跳转支付页
        }else{
            return packJson('',$finnal_return_value['message'],500);
        }
    }
    public function backUrl(){
        Db::startTrans();
        //参与签名
        $pay['merId'] = input('merId' , '');//测试商户号
        $pay['finalOrderId'] =  input('finalOrderId' , '');
        $pay['merOrderId'] =  input('merOrderId' , '');
        $pay['succTime'] =  input('succTime' , '');
        $pay['transAmt'] =  input('transAmt' , '');
        //不参与签名
        $pay['respCode'] =  input('respCode' , '');
        $pay['merResv'] =  input('merResv' , '');
        $pay['respMsg'] =  input('respMsg' , '');
        //服务器端签名结果
        $server_sign_result =  input('sign' , '');
        ksort($pay);
        $client_sign = strtoupper(md5($this->signMsg($pay, $this->key)));
        if ( $server_sign_result==$client_sign && '60006' == $pay['respCode'] ) {
            //更新用户金额、打码量等相关信息
            $order_info = Db::name('chongzhi_list')->where('ddbh',$pay['merOrderId'])->find();
            if($order_info['je'] != sprintf("%.2f",floatval($pay['transAmt'])/100)) return 'error';
            $user_info = Db::name('username')->where('username',$order_info['username'])->find();
            $dml_set = Db::name('xt_dmsz')->where('id',1)->find();
            $xtcz = Db::name('xt_chongzhi')->where('id',1)->find();
            if($xtcz['dmopen'] == 1) {
                $dmls = ($order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['je'] + $order_info['method_money']) * $dml_set['xscz_dmbs'];
            }else{
                $dmls = $order_info['je'] * $dml_set['xscz_dmbs'];
            }
            //充值后账户总金额
            $czhje = $order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['je'] + $user_info['je'] + $order_info['method_money'];
            //充值总金额
            $czzje = $order_info['je'] + $user_info['czzje'];
            //用户当前打码量
            $dml = $user_info['dml'] + $dmls;
            try {
                $zt = model('ChongzhiList')->where(['ddbh'=>$pay['merOrderId']])->value('zt');
                if( 1==intval($zt) ){
                    throw new Exception("该订单已经成功通知");
                }
                if( !model('ChongzhiList')->updateRechargeInfo($pay['merOrderId'],$pay['finalOrderId'],1,$czhje,time()) ){
                    throw new Exception("更新订单信息错误");
                }
                if( !model('Username')->upUserXsczInfo($czhje,$dml,$czzje,$order_info['username']) ){
                    throw new Exception("更新用户金额错误");
                }
                $fav_money = $order_info['hy_msje']+$order_info['hy_zsje']+ $order_info['method_money'];

                //满送金额，等级赠送金额，充值方案赠送金额
                $extcj = array(
                    'username'=>$user_info['username'],
                    'user_class'=>$user_info['us_class'],
                    'fstime'=>time(),
                    'czadmin' => '系统赠送',
                );
                $cjhje = floatval($order_info['je']) + floatval($user_info['je']) + floatval($order_info['hy_msje']);
                if( floatval($order_info['hy_msje']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值满送金额';
                    $extcj['cjje'] = $order_info['hy_msje'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
                $cjhje += floatval($order_info['hy_zsje']);
                if( floatval($order_info['hy_zsje']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值等级赠送金额';
                    $extcj['cjje'] = $order_info['hy_zsje'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
                $cjhje += floatval($order_info['method_money']);
                if( floatval($order_info['method_money']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值方案赠送金额';
                    $extcj['cjje'] = $order_info['method_money'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }

                Db::name('username')->where('username',$order_info['username'])->setInc('cz_num');
                $data = array('username' =>$order_info['username'],'test'=>"您账户充值金额：{$order_info['je']}，赠送金额：{$fav_money}。已充值到账，请注意查收！",'xx_time'=>time(),'ifdq'=>0);
                Db::name('xiaoxi')->data($data)->insert();
                Db::commit();
                return 'ok';
            } catch (\Exception $e) {
                Db::rollback();
                return 'error';
            }
        }
        return 'error';
    }
    public function returnUrl(){
        //参与签名
        $pay['merId'] = input('merId' , '');//测试商户号
        $pay['finalOrderId'] =  input('finalOrderId' , '');
        $pay['merOrderId'] =  input('merOrderId' , '');
        $pay['succTime'] =  input('succTime' , '');
        $pay['transAmt'] =  input('transAmt' , '');
        //不参与签名
        $pay['respCode'] =  input('respCode' , '');
        $pay['merResv'] =  input('merResv' , '');
        $pay['respMsg'] =  input('respMsg' , '');
        //服务器端签名结果
        $server_sign_result =  input('sign' , '');
        ksort($pay);
        $client_sign = strtoupper(md5($this->signMsg($pay, $this->key)));

        if ( $server_sign_result==$client_sign && '60006' == $pay['respCode'] ) {
            $amount = sprintf("%.2f",$pay['transAmt']/100);
            $this->buildHtml("充值成功，{$amount} 元已到账");
        }else{
            $this->buildHtml("充值失败");
        }
    }
    public function returnUrlThird(){
        //参与签名
        $pay['merId'] = input('merId' , '');//测试商户号
        $pay['finalOrderId'] =  input('finalOrderId' , '');
        $pay['merOrderId'] =  input('merOrderId' , '');
        $pay['succTime'] =  input('succTime' , '');
        $pay['transAmt'] =  input('transAmt' , '');
        //不参与签名
        $pay['respCode'] =  input('respCode' , '');
        $pay['merResv'] =  input('merResv' , '');
        $pay['respMsg'] =  input('respMsg' , '');
        //服务器端签名结果
        $server_sign_result =  input('sign' , '');
        ksort($pay);
        $client_sign = strtoupper(md5($this->signMsg($pay, $this->key)));

        if ( $server_sign_result==$client_sign && '60006' == $pay['respCode'] ) {
            $amount = sprintf("%.2f",$pay['transAmt']/100);
            $this->buildHtml("充值成功，{$amount} 元已到账",1);
        }else{
            $this->buildHtml("充值失败",1);
        }
    }
    /**
     * 设置加签数据
     * @param $array
     * @param $md5Key
     * @return string
     */
    function signMsg($array,$md5Key){
        $msg = "";
        // 转换为字符串 key=value&key.... 加签
        foreach ($array as $key => $val) {
            // 不参与签名
            if($key != "goodsTitle" && $key != "goodsDesc" && $key != "sendIp" && $key != "merResv" && $key != "bankCode" && $key != "returnUrl" && $key != "sign" && $key != "respMsg"){
                $msg = $msg."&$key=$val";

            }
        }
        $msg = $msg.$md5Key;
        return  $msg;
    }
}
class HttpClient {
    // Request vars
    var $host;
    var $port;
    var $path;
    var $method;
    var $postdata = '';
    var $cookies = array();
    var $referer;
    var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
    var $accept_encoding = 'gzip';
    var $accept_language = 'en-us';
    var $user_agent = 'Incutio HttpClient v0.9';
    // Options
    var $timeout = 20;
    var $use_gzip = true;
    var $persist_cookies = true;  // If true, received cookies are placed in the $this->cookies array ready for the next request
    // Note: This currently ignores the cookie path (and time) completely. Time is not important,
    //       but path could possibly lead to security problems.
    var $persist_referers = true; // For each request, sends path of last request as referer
    var $debug = false;
    var $handle_redirects = true; // Auaomtically redirect if Location or URI header is found
    var $max_redirects = 5;
    var $headers_only = false;    // If true, stops receiving once headers have been read.
    // Basic authorization variables
    var $username;
    var $password;
    // Response vars
    var $status;
    var $headers = array();
    var $content = '';
    var $errormsg;
    // Tracker variables
    var $redirect_count = 0;
    var $cookie_host = '';
    function __construct($host, $port=80) {
        $this->host = $host;
        $this->port = $port;
    }
    function get($path, $data = false) {
        $this->path = $path;
        $this->method = 'GET';
        if ($data) {
            $this->path .= '?'.$this->buildQueryString($data);
        }
        return $this->doRequest();
    }
    function post($path, $data) {
        $this->path = $path;
        $this->method = 'POST';
        $this->postdata = $this->buildQueryString($data);
        return $this->doRequest();
    }
    function buildQueryString($data) {
        $querystring = '';
        if (is_array($data)) {
            // Change data in to postable data
            foreach ($data as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $val2) {
                        $querystring .= urlencode($key).'='.urlencode($val2).'&';
                    }
                } else {
                    $querystring .= urlencode($key).'='.urlencode($val).'&';
                }
            }
            $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
        } else {
            $querystring = $data;
        }
        return $querystring;
    }
    function doRequest() {
        // Performs the actual HTTP request, returning true or false depending on outcome
        if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
            // Set error message
            switch($errno) {
                case -3:
                    $this->errormsg = 'Socket creation failed (-3)';
                case -4:
                    $this->errormsg = 'DNS lookup failure (-4)';
                case -5:
                    $this->errormsg = 'Connection refused or timed out (-5)';
                default:
                    $this->errormsg = 'Connection failed ('.$errno.')';
                    $this->errormsg .= ' '.$errstr;
                    $this->debug($this->errormsg);
            }
            return false;
        }
        socket_set_timeout($fp, $this->timeout);
        $request = $this->buildRequest();
        $this->debug('Request', $request);
        fwrite($fp, $request);
        // Reset all the variables that should not persist between requests
        $this->headers = array();
        $this->content = '';
        $this->errormsg = '';
        // Set a couple of flags
        $inHeaders = true;
        $atStart = true;
        // Now start reading back the response
        while (!feof($fp)) {
            $line = fgets($fp, 4096);
            if ($atStart) {
                // Deal with first line of returned data
                $atStart = false;
                if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
                    $this->errormsg = "Status code line invalid: ".htmlentities($line);
                    $this->debug($this->errormsg);
                    return false;
                }
                $http_version = $m[1]; // not used
                $this->status = $m[2];
                $status_string = $m[3]; // not used
                $this->debug(trim($line));
                continue;
            }
            if ($inHeaders) {
                if (trim($line) == '') {
                    $inHeaders = false;
                    $this->debug('Received Headers', $this->headers);
                    if ($this->headers_only) {
                        break; // Skip the rest of the input
                    }
                    continue;
                }
                if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
                    // Skip to the next header
                    continue;
                }
                $key = strtolower(trim($m[1]));
                $val = trim($m[2]);
                // Deal with the possibility of multiple headers of same name
                if (isset($this->headers[$key])) {
                    if (is_array($this->headers[$key])) {
                        $this->headers[$key][] = $val;
                    } else {
                        $this->headers[$key] = array($this->headers[$key], $val);
                    }
                } else {
                    $this->headers[$key] = $val;
                }
                continue;
            }
            // We're not in the headers, so append the line to the contents
            $this->content .= $line;
        }
        fclose($fp);
        // If data is compressed, uncompress it
        if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
            $this->debug('Content is gzip encoded, unzipping it');
            $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php
            $this->content = gzinflate($this->content);
        }
        // If $persist_cookies, deal with any cookies
        if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) {
            $cookies = $this->headers['set-cookie'];
            if (!is_array($cookies)) {
                $cookies = array($cookies);
            }
            foreach ($cookies as $cookie) {
                if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
                    $this->cookies[$m[1]] = $m[2];
                }
            }
            // Record domain of cookies for security reasons
            $this->cookie_host = $this->host;
        }
        // If $persist_referers, set the referer ready for the next request
        if ($this->persist_referers) {
            $this->debug('Persisting referer: '.$this->getRequestURL());
            $this->referer = $this->getRequestURL();
        }
        // Finally, if handle_redirects and a redirect is sent, do that
        if ($this->handle_redirects) {
            if (++$this->redirect_count >= $this->max_redirects) {
                $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')';
                $this->debug($this->errormsg);
                $this->redirect_count = 0;
                return false;
            }
            $location = isset($this->headers['location']) ? $this->headers['location'] : '';
            $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
            if ($location || $uri) {
                $url = parse_url($location.$uri);
                // This will FAIL if redirect is to a different site
                return $this->get($url['path']);
            }
        }
        return true;
    }
    function buildRequest() {
        $headers = array();
        $headers[] = "{$this->method} {$this->path} HTTP/1.0"; // Using 1.1 leads to all manner of problems, such as "chunked" encoding
        $headers[] = "Host: {$this->host}";
        $headers[] = "User-Agent: {$this->user_agent}";
        $headers[] = "Accept: {$this->accept}";
        if ($this->use_gzip) {
            $headers[] = "Accept-encoding: {$this->accept_encoding}";
        }
        $headers[] = "Accept-language: {$this->accept_language}";
        if ($this->referer) {
            $headers[] = "Referer: {$this->referer}";
        }
        // Cookies
        if ($this->cookies) {
            $cookie = 'Cookie: ';
            foreach ($this->cookies as $key => $value) {
                $cookie .= "$key=$value; ";
            }
            $headers[] = $cookie;
        }
        // Basic authentication
        if ($this->username && $this->password) {
            $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
        }
        // If this is a POST, set the content type and length
        if ($this->postdata) {
            $headers[] = 'Content-Type: application/x-www-form-urlencoded';
            $headers[] = 'Content-Length: '.strlen($this->postdata);
        }
        $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata;
        return $request;
    }
    function getStatus() {
        return $this->status;
    }
    function getContent() {
        return $this->content;
    }
    function getHeaders() {
        return $this->headers;
    }
    function getHeader($header) {
        $header = strtolower($header);
        if (isset($this->headers[$header])) {
            return $this->headers[$header];
        } else {
            return false;
        }
    }
    function getError() {
        return $this->errormsg;
    }
    function getCookies() {
        return $this->cookies;
    }
    function getRequestURL() {
        $url = 'http://'.$this->host;
        if ($this->port != 80) {
            $url .= ':'.$this->port;
        }
        $url .= $this->path;
        return $url;
    }
    // Setter methods
    function setUserAgent($string) {
        $this->user_agent = $string;
    }
    function setAuthorization($username, $password) {
        $this->username = $username;
        $this->password = $password;
    }
    function setCookies($array) {
        $this->cookies = $array;
    }
    // Option setting methods
    function useGzip($boolean) {
        $this->use_gzip = $boolean;
    }
    function setPersistCookies($boolean) {
        $this->persist_cookies = $boolean;
    }
    function setPersistReferers($boolean) {
        $this->persist_referers = $boolean;
    }
    function setHandleRedirects($boolean) {
        $this->handle_redirects = $boolean;
    }
    function setMaxRedirects($num) {
        $this->max_redirects = $num;
    }
    function setHeadersOnly($boolean) {
        $this->headers_only = $boolean;
    }
    function setDebug($boolean) {
        $this->debug = $boolean;
    }
    // "Quick" static methods
    function quickGet($url) {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        if (isset($bits['query'])) {
            $path .= '?'.$bits['query'];
        }
        $client = new HttpClient($host, $port);
        if (!$client->get($path)) {
            return false;
        } else {
            return $client->getContent();
        }
    }
    static function  quickPost($url, $data) {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        $client = new HttpClient($host, $port);
        if (!$client->post($path, $data)) {
            return false;
        } else {
            return $client->getContent();
        }
    }
    function debug($msg, $object = false) {
        if ($this->debug) {
            print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg;
            if ($object) {
                ob_start();
                print_r($object);
                $content = htmlentities(ob_get_contents());
                ob_end_clean();
                print '<pre>'.$content.'</pre>';
            }
            print '</div>';
        }
    }
}

